#!/bin/bash

# CLU API Service Docker构建和部署脚本
# 支持开发和生产环境的快速部署

set -e  # 遇到错误立即退出

# ====================================
# 配置变量
# ====================================
IMAGE_NAME="clu-api-service"
CONTAINER_NAME="clu-api-service"
DEFAULT_TAG="latest"
DEFAULT_ENV="dev"

# ====================================
# 颜色输出函数
# ====================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# ====================================
# 帮助信息
# ====================================
show_help() {
    echo "CLU API Service Docker构建和部署脚本"
    echo ""
    echo "用法: $0 [选项] <命令>"
    echo ""
    echo "命令:"
    echo "  build     构建Docker镜像"
    echo "  run       运行容器"
    echo "  stop      停止容器"
    echo "  restart   重启容器"
    echo "  logs      查看容器日志"
    echo "  clean     清理容器和镜像"
    echo "  deploy    部署到生产环境"
    echo ""
    echo "选项:"
    echo "  -t, --tag TAG        镜像标签 (默认: $DEFAULT_TAG)"
    echo "  -e, --env ENV        环境类型 dev|prod (默认: $DEFAULT_ENV)"
    echo "  -h, --help           显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 build -t v1.0.0"
    echo "  $0 run -e prod"
    echo "  $0 deploy -t v1.0.0 -e prod"
}

# ====================================
# 参数解析
# ====================================
TAG="$DEFAULT_TAG"
ENV="$DEFAULT_ENV"
COMMAND=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--tag)
            TAG="$2"
            shift 2
            ;;
        -e|--env)
            ENV="$2"
            shift 2
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        build|run|stop|restart|logs|clean|deploy)
            COMMAND="$1"
            shift
            ;;
        *)
            log_error "未知参数: $1"
            show_help
            exit 1
            ;;
    esac
done

# ====================================
# 检查必需的文件
# ====================================
check_requirements() {
    log_info "检查构建要求..."
    
    if [[ ! -f "Dockerfile" ]]; then
        log_error "Dockerfile不存在"
        exit 1
    fi
    
    if [[ ! -f "pyproject.toml" ]]; then
        log_error "pyproject.toml不存在"
        exit 1
    fi
    
    if [[ ! -f "uv.lock" ]]; then
        log_warning "uv.lock不存在，建议运行 'uv sync' 生成锁定文件"
    fi
    
    if [[ "$ENV" == "prod" && ! -f ".env.prod" ]]; then
        log_warning ".env.prod不存在，将使用.env文件"
    elif [[ "$ENV" == "dev" && ! -f ".env" ]]; then
        log_warning ".env不存在，请确保环境变量已正确设置"
    fi
    
    log_success "构建要求检查完成"
}

# ====================================
# 构建镜像
# ====================================
build_image() {
    log_info "开始构建Docker镜像..."
    log_info "镜像名称: ${IMAGE_NAME}:${TAG}"
    log_info "环境类型: ${ENV}"
    
    check_requirements
    
    # 构建参数
    BUILD_ARGS=""
    if [[ "$ENV" == "prod" ]]; then
        BUILD_ARGS="--target runtime"
    fi
    
    # 执行构建
    docker build $BUILD_ARGS -t "${IMAGE_NAME}:${TAG}" .
    
    # 如果是latest标签，同时打上环境标签
    if [[ "$TAG" == "latest" ]]; then
        docker tag "${IMAGE_NAME}:${TAG}" "${IMAGE_NAME}:${ENV}"
    fi
    
    log_success "镜像构建完成: ${IMAGE_NAME}:${TAG}"
}

# ====================================
# 运行容器
# ====================================
run_container() {
    log_info "启动容器..."
    
    # 停止现有容器
    if docker ps -q -f name="$CONTAINER_NAME" | grep -q .; then
        log_info "停止现有容器..."
        docker stop "$CONTAINER_NAME" || true
        docker rm "$CONTAINER_NAME" || true
    fi
    
    # 选择compose文件
    COMPOSE_FILE="docker-compose.yml"
    if [[ "$ENV" == "prod" ]]; then
        COMPOSE_FILE="docker-compose.prod.yml"
    fi
    
    # 启动服务
    if [[ -f "$COMPOSE_FILE" ]]; then
        log_info "使用docker-compose启动服务..."
        docker-compose -f "$COMPOSE_FILE" up -d
    else
        log_info "使用docker run启动容器..."
        # 准备宿主机日志目录，并确保权限
        mkdir -p "$(pwd)/logs" && chmod 775 "$(pwd)/logs"
        # 以当前用户的 UID:GID 运行，避免挂载卷权限问题
        docker run -d \
            --name "$CONTAINER_NAME" \
            -p 8055:8055 \
            --env-file .env \
            -v "$(pwd)/logs:/app/logs" \
            --user "$(id -u):$(id -g)" \
            "${IMAGE_NAME}:${TAG}"
    fi
    
    log_success "容器启动完成"
    log_info "API文档地址: http://localhost:8055/docs"
}

# ====================================
# 停止容器
# ====================================
stop_container() {
    log_info "停止容器..."
    
    # 使用docker-compose停止
    COMPOSE_FILE="docker-compose.yml"
    if [[ "$ENV" == "prod" ]]; then
        COMPOSE_FILE="docker-compose.prod.yml"
    fi
    
    if [[ -f "$COMPOSE_FILE" ]]; then
        docker-compose -f "$COMPOSE_FILE" down
    else
        docker stop "$CONTAINER_NAME" || true
        docker rm "$CONTAINER_NAME" || true
    fi
    
    log_success "容器已停止"
}

# ====================================
# 重启容器
# ====================================
restart_container() {
    log_info "重启容器..."
    stop_container
    run_container
}

# ====================================
# 查看日志
# ====================================
show_logs() {
    log_info "显示容器日志..."
    
    COMPOSE_FILE="docker-compose.yml"
    if [[ "$ENV" == "prod" ]]; then
        COMPOSE_FILE="docker-compose.prod.yml"
    fi
    
    if [[ -f "$COMPOSE_FILE" ]]; then
        docker-compose -f "$COMPOSE_FILE" logs -f
    else
        docker logs -f "$CONTAINER_NAME"
    fi
}

# ====================================
# 清理资源
# ====================================
clean_resources() {
    log_info "清理Docker资源..."
    
    # 停止并删除容器
    stop_container
    
    # 删除镜像
    log_info "删除镜像..."
    docker rmi "${IMAGE_NAME}:${TAG}" || true
    docker rmi "${IMAGE_NAME}:${ENV}" || true
    
    # 清理未使用的资源
    log_info "清理未使用的Docker资源..."
    docker system prune -f
    
    log_success "清理完成"
}

# ====================================
# 部署到生产环境
# ====================================
deploy_production() {
    log_info "部署到生产环境..."
    
    ENV="prod"
    
    # 构建生产镜像
    build_image
    
    # 运行生产容器
    run_container
    
    # 健康检查
    log_info "等待服务启动..."
    sleep 10
    
    if curl -f http://localhost:8055/docs > /dev/null 2>&1; then
        log_success "生产环境部署成功!"
        log_info "API文档地址: http://localhost:8055/docs"
    else
        log_error "服务健康检查失败"
        show_logs
        exit 1
    fi
}

# ====================================
# 主逻辑
# ====================================
main() {
    if [[ -z "$COMMAND" ]]; then
        log_error "请指定命令"
        show_help
        exit 1
    fi
    
    case "$COMMAND" in
        build)
            build_image
            ;;
        run)
            run_container
            ;;
        stop)
            stop_container
            ;;
        restart)
            restart_container
            ;;
        logs)
            show_logs
            ;;
        clean)
            clean_resources
            ;;
        deploy)
            deploy_production
            ;;
        *)
            log_error "未知命令: $COMMAND"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
